package com.ywy.search.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywy.search.model.PostDocument;
import com.ywy.search.mq.MqPostMessage;
import com.ywy.search.repository.PostRepository;
import com.ywy.search.service.ESService;
import com.ywy.mapper.PostMapper;
import com.ywy.vo.PostVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * ESSerivce实现
 *
 * @author ywy
 * @date 2021/12/30 14:08
 */
@Slf4j
@Service
public class ESServiceImpl implements ESService {
    @Autowired
    private PostRepository postRepository;
    @Autowired
    private PostMapper postMapper;

    @Override
    public IPage search(Page page, String keyword) {
        // 分页信息，mybatis-plus的page转成jpa的pageable
        Long current = page.getCurrent() - 1;
        Long size = page.getSize();

        // 搜索es，多个字段匹配，只要满足一个即可返回结果
        Pageable pageable = PageRequest.of(current.intValue(), size.intValue());
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(keyword, "title", "authorName", "categoryName");
        org.springframework.data.domain.Page<PostDocument> documents = postRepository.search(multiMatchQueryBuilder, pageable);
        log.info("查询 {} 得到 {} 个查询结果，一共 {} 页", keyword, documents.getTotalElements(), documents.getTotalPages());

        // 搜索结果，jpa的page转成mybatis-plus的page
        IPage pageData = new Page(page.getCurrent(), page.getSize(), documents.getTotalElements());
        pageData.setRecords(documents.getContent());
        return pageData;
    }

    @Override
    public int initEsIndex(List<PostVo> records) {
        if (records == null || records.isEmpty()) {
            return 0;
        }

        List<PostDocument> documents = new ArrayList<>();
        for (PostVo vo : records) {
            // 映射转换
            PostDocument postDocument = new PostDocument();
            BeanUtils.copyProperties(vo, postDocument);
            documents.add(postDocument);
        }

        // 批量保存数据到ES
        postRepository.saveAll(documents);
        return documents.size();
    }

    @Override
    public void createOrUpdateIndex(MqPostMessage message) {
        // 查询要修改的数据
        Integer postId = message.getPostId();
        PostVo postVo = postMapper.getDetail(postId);

        // 更新ES数据
        PostDocument postDocument = new PostDocument();
        BeanUtils.copyProperties(postVo, postDocument);
        postRepository.save(postDocument);
        log.info("ES索引更新成功：{}", message);
    }

    @Override
    public void removeIndex(MqPostMessage message) {
        // 删除ES数据
        Integer postId = message.getPostId();
        postRepository.deleteById(postId);
        log.info("ES索引删除成功：{}", message);
    }
}
